﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sitecore.Data.Items;
using System.Data;

namespace Workflow.Alerts.Sublayouts
{
    public partial class ListFilter : BaseControl, IFilterView
    {
        #region IFilterView Members

        public Dictionary<int, string> AlertTypeList
        {
            set
            {
                chkAlertType.Items.Clear();
                if (value.Any())
                {
                    foreach (var item in value)
                    {
                        ListItem li = new ListItem()
                        {
                            Value = item.Key.ToString(),
                            Text = item.Value
                        };
                        li.Attributes.Add("class", "radioButton");
                        chkAlertType.Items.Add(li);
                    }
                }
                else
                {
                    alerttype.Visible = false;
                }
            }
        }

        public List<int> SelectedAlertType
        {
            get
            {
                var selectedItems =
                from item in chkAlertType.Items.Cast<ListItem>()
                where item.Selected == true
                select Int32.Parse(item.Value);
                return selectedItems.ToList<int>();

            }
            set
            {
                foreach (Int32 key in value)
                {
                    chkAlertType.Items.FindByValue(key.ToString()).Selected = true;
                }
            }
        }

        public Dictionary<int, string> ActivityTypeList
        {
            set
            {
                chkActivityType.Items.Clear();
                if (value.Any())
                {

                    foreach (var item in value)
                    {
                        ListItem li = new ListItem()
                        {
                            Value = item.Key.ToString(),
                            Text = item.Value
                        };
                        li.Attributes.Add("class", "radioButton");
                        chkActivityType.Items.Add(li);
                    }
                }
                else
                {
                    activitytype.Visible = false;
                }
            }
        }

        public List<int> SelectedActivityType
        {
            get
            {
                var selectedItems =
                from item in chkActivityType.Items.Cast<ListItem>()
                where item.Selected == true
                select Int32.Parse(item.Value);
                return selectedItems.ToList<int>();

            }
            set
            {
                foreach (Int32 key in value)
                {
                    chkActivityType.Items.FindByValue(key.ToString()).Selected = true;
                }
            }
        }

        public DataTable NetworkOperatorList
        {
            set
            {
                chkNetworkOperator.Items.Clear();
                if (value.Rows.Count == 0)
                {
                    networkoperatorname.Visible = false;
                }
                else
                {
                    foreach (DataRow item in value.Rows)
                    {
                        ListItem li = new ListItem()
                        {
                            Value = item["id"].ToString(),
                            Text = item["name"].ToString()
                        };
                        li.Attributes.Add("class", "radioButton");
                        chkNetworkOperator.Items.Add(li);
                    }
                }
            }
        }

        public List<int> SelectedNetworkOperator
        {
            get
            {
                var selectedItems =
                from item in chkNetworkOperator.Items.Cast<ListItem>()
                where item.Selected == true
                select Int32.Parse(item.Value);
                return selectedItems.ToList<int>();

            }
            set
            {
                foreach (Int32 key in value)
                {
                    chkNetworkOperator.Items.FindByValue(key.ToString()).Selected = true;
                }
            }
        }

        public Dictionary<int, string> StatusList
        {
            set
            {
                chkStatus.Items.Clear();

                if (value.Any())
                {
                    foreach (var item in value)
                    {
                        ListItem li = new ListItem()
                        {
                            Value = item.Key.ToString(),
                            Text = item.Value
                        };
                        li.Attributes.Add("class", "radioButton");
                        chkStatus.Items.Add(li);
                    }
                }
                else
                {
                    status.Visible = false;
                }
            }
        }

        public List<int> SelectedSatuses
        {
            get
            {
                var selectedItems =
                from item in chkStatus.Items.Cast<ListItem>()
                where item.Selected == true
                select Int32.Parse(item.Value);
                return selectedItems.ToList<int>();

            }
            set
            {
                foreach (Int32 key in value)
                {
                    chkStatus.Items.FindByValue(key.ToString()).Selected = true;
                }
            }
        }

        Dictionary<string, string> IFilterView.Dates
        {
            set
            {
                ddlDate.Items.Clear();
                ddlDate.DataSource = value;
                ddlDate.DataTextField = "value";
                ddlDate.DataValueField = "key";
                ddlDate.DataBind();
            }
        }

        public DataTable MunicipalityList
        {
            set
            {
                chkMunicipality.Items.Clear();
                if (value.Rows.Count == 0)
                {
                    municipalityname.Visible = false;
                }
                else
                {
                    foreach (DataRow item in value.Rows)
                    {
                        ListItem li = new ListItem()
                        {
                            Value = item["id"].ToString(),
                            Text = item["name"].ToString()
                        };
                        li.Attributes.Add("class", "radioButton");
                        chkMunicipality.Items.Add(li);
                    }
                }
            }
        }

        public List<int> SelectedMunicipality
        {
            get
            {
                var selectedItems =
                from item in chkMunicipality.Items.Cast<ListItem>()
                where item.Selected == true
                select Int32.Parse(item.Value);
                return selectedItems.ToList<int>();
            }
            set
            {
                foreach (Int32 key in value)
                {
                    chkMunicipality.Items.FindByValue(key.ToString()).Selected = true;
                }
            }
        }

        public Dictionary<int, string> ContractorList
        {
            set
            {
                ddlContractors.DataSource = value;
                ddlContractors.DataTextField = "value";
                ddlContractors.DataValueField = "key";
                ddlContractors.DataBind();

                ddlContractors.Items.Insert(0, new ListItem("Allemaal", "-1"));
            }
        }

        public Int32? Contractor
        {
            get
            {
                if (ddlContractors.SelectedItem == null ||
                    ddlContractors.SelectedValue == "-1")
                    return null;
                else
                    return Int32.Parse(ddlContractors.SelectedValue);
            }

            set
            {
                if (ddlContractors.Items.Count > 0 &&
                    value.HasValue &&
                    ddlContractors.Items.FindByValue(value.Value.ToString()) != null)
                {
                    ddlContractors.Items.FindByValue(value.Value.ToString()).Selected = true;
                }
            }
        }

        public Boolean IsHerstel{
            get{
                return chkHerstel.Checked;
                }
            set
            {
                chkHerstel.Checked = value;
            }
        }

        public event OnFilterLoad FilterLoad;

        public event OnFilterApply FilterApply;

        #endregion

        #region Properties
        Dictionary<string, DateTime> FilterDates
        {
            get
            {
                if (Session[WorkflowConstants.FilterDates] == null)
                    Session[WorkflowConstants.FilterDates] = new Dictionary<string, DateTime>();
                return Session[WorkflowConstants.FilterDates] as Dictionary<string, DateTime>;
            }
            set
            {
                Session[WorkflowConstants.FilterDates] = value;
            }
        }
        #endregion

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            PresentationManager.RegisterView(typeof(FilterViewPresenter), this, new WebSessionProvider());

            Sitecore.Data.Fields.MultilistField filterColumns = (Sitecore.Data.Fields.MultilistField)Sitecore.Context.Item.Fields["Filtersettings"];

            if (filterColumns != null)
            {
                var visibleFilterColumns = filterColumns.GetItems();

                foreach (Item item in visibleFilterColumns)
                {
                    var field = item.Name.Replace(" ", "").ToLower();
                    var control = filter.FindControlRecursive(field);
                    if (control != null) control.Visible = true;
                }
            }

            if (!IsPostBack && FilterLoad != null)
            {
                FilterLoad();
                LoadDates();

            }

            if (Sitecore.Context.Item.Parent.Name == WorkflowConstants.Logged)
                herstel.Visible = true;
        }

        protected void btnApply_Click(object sender, EventArgs e)
        {
            if (FilterApply != null)
            {
                FilterApply();
                FilterLoad();
                LoadDates();
            }
        }

        protected void btnEraseFilter_Click(object sender, EventArgs e)
        {
            Session[WorkflowConstants.Filters] = null;
            FilterDates = null;
        }

        protected void ddlDate_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDates();
        }

        protected void rdpFromDate_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
        {
            StoreFromDate();
        }

        protected void rdpToDate_SelectedDateChanged(object sender, Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs e)
        {
            StoreToDate();
        }

        protected void chkFromDate_CheckedChanged(object sender, EventArgs e)
        {
            rdpFromDate.Enabled = chkFromDate.Checked;
            if (!chkFromDate.Checked)
                rdpFromDate.SelectedDate = null;
        }

        protected void chkToDate_CheckedChanged(object sender, EventArgs e)
        {
            rdpToDate.Enabled = chkToDate.Checked;
            if (!chkToDate.Checked)
                rdpToDate.SelectedDate = null;
        }
        #endregion

        #region Private methods
        private void StoreFromDate()
        {
            string dateField = ddlDate.SelectedItem.Value;
            string fromDate = string.Concat("from_", dateField);

            if (chkFromDate.Checked)
            {
                FilterDates[fromDate] = rdpFromDate.SelectedDate.Value;
            }
            else
            {
                if (FilterDates.ContainsKey(fromDate))
                    FilterDates.Remove(fromDate);
            }
        }

        private void StoreToDate()
        {
            string dateField = ddlDate.SelectedItem.Value;
            string toDate = string.Concat("to_", dateField);

            if (chkToDate.Checked)
            {
                FilterDates[toDate] = rdpToDate.SelectedDate.Value;
            }
            else
            {
                if (FilterDates.ContainsKey(toDate))
                    FilterDates.Remove(toDate);
            }
        }

        private void LoadDates()
        {
            string dateField = ddlDate.SelectedItem.Value;
            string fromDate = string.Concat("from_", dateField);
            string toDate = string.Concat("to_", dateField);

            if (FilterDates.ContainsKey(fromDate) && FilterDates[fromDate] != null)
            {
                chkFromDate.Checked = true;
                rdpFromDate.SelectedDate = (DateTime)FilterDates[fromDate];
            }
            else
            {
                chkFromDate.Checked = false;
                rdpFromDate.SelectedDate = null;
            }


            if (FilterDates.ContainsKey(toDate) && FilterDates[toDate] != null)
            {
                chkToDate.Checked = true;
                rdpToDate.SelectedDate = (DateTime)FilterDates[toDate];
            }
            else
            {
                chkToDate.Checked = false;
                rdpToDate.SelectedDate = null;
            }

        }

        #endregion
    }
}